import { existsSync, mkdirSync, writeFileSync } from "fs";
import { App, FileSystemAdapter, MarkdownView, Plugin_2 } from "obsidian";
import { join, resolve } from "path";
import { format } from "./utils";
import {Handler} from "./handle";

export default class LocalSaveHandler implements Handler {

    async handle(file: File, plugin: Plugin_2): Promise<void> {
        console.log(file)
        const folderPath = this.getFileAssetPath(plugin.app)
        if (!existsSync(folderPath)) {
            mkdirSync(folderPath)
        }
        let name = file.name
        if (name == null || name == "" || existsSync(join(folderPath, name))) {
            name = `file-${format(new Date())}`
            if (file.type.startsWith("image")) {
                console.log(file.type)
            }
        }
        const fileData = await file.arrayBuffer()
        console.log(name)
        writeFileSync(join(folderPath, name), new Uint8Array(Buffer.from(fileData)))
        const mdView = plugin.app.workspace.activeLeaf.view as MarkdownView
        const editor = mdView.editor
        editor.replaceSelection(`${join(folderPath, name)}\n`);
    }


    // 获取当前文件所属的附件文件夹
    getFileAssetPath(app: App) {
        const basePath = (
            app.vault.adapter as FileSystemAdapter
        ).getBasePath();
        
        // @ts-ignore
        const assetFolder: string = this.app.vault.config.attachmentFolderPath;
        const activeFile = app.vault.getAbstractFileByPath(
            app.workspace.getActiveFile().path
        );

        // 当前文件夹下的子文件夹
        if (assetFolder.startsWith("./")) {
            const activeFolder = decodeURI(resolve(basePath, activeFile.parent.path));
            return join(activeFolder, assetFolder);
        } else {
            // 根文件夹
            return join(basePath, assetFolder);
        }
    }
}